import { AvatarDropdown, AvatarName, Footer } from "@/components";
import { currentUser as queryCurrentUser } from "@/services/ant-design-pro/api";
import type { Settings as LayoutSettings } from "@ant-design/pro-components";
import "@ant-design/v5-patch-for-react-19";
import type { RequestConfig, RunTimeLayoutConfig } from "@umijs/max";
import { history } from "@umijs/max";
import defaultSettings from "../config/defaultSettings";
import { errorConfig } from "./requestErrorConfig";

import routes from "../config/routes"; // 导入路由配置
const isDev = process.env.NODE_ENV === "development";
const loginPath = "/user/login";
/**
 * @see https://umijs.org/docs/api/runtime-config#getinitialstate
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (_error) {
      // history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  // if (
  //   ![loginPath, '/user/register', '/user/register-result'].includes(
  //     location.pathname,
  //   )
  // ) {
  //   const currentUser = await fetchUserInfo();
  //   return {
  //     fetchUserInfo,
  //     currentUser,
  //     settings: defaultSettings as Partial<LayoutSettings>,
  //   };
  // }
  return {
    fetchUserInfo,
    settings: {
      ...(defaultSettings as Partial<LayoutSettings>),
    },
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  console.log(initialState, "initialState111");
  return {
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        const authority = localStorage.getItem("authority");
        const nickname = localStorage.getItem("nickname");
        console.log(nickname, "nicknamenickname");
        let title: string = "";
        switch (authority) {
          case "1":
            title = "超级管理员";
            break;
          case "2":
            title = "出库管理员";
            break;
          case "3":
            title = "人事管理员";
            break;
          case "4":
            title = "采购管理员";
            break;
          default:
            "";
        }

        return (
          <AvatarDropdown>{`${nickname || ""} (${title})`}</AvatarDropdown>
        );
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      // if (!initialState?.currentUser && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }

      const findParentRouteByPath = (path: any, routes: any) => {
        const normalizedPath = path.startsWith("/") ? path : `/${path}`;
        for (const route of routes) {
          // 1. 检查是否直接匹配一级路由路径
          if (route.path === normalizedPath) {
            return route;
          }

          // 2. 检查是否匹配一级路由的重定向路径
          if (route.redirect === normalizedPath) {
            return route;
          }

          // 3. 检查是否匹配子路由路径
          if (route.routes && Array.isArray(route.routes)) {
            for (const subRoute of route.routes) {
              // 检查子路由路径
              if (subRoute.path === normalizedPath) {
                return route; // 返回父级路由
              }

              // 检查子路由的重定向路径
              if (subRoute.redirect === normalizedPath) {
                return route; // 返回父级路由
              }
            }
          }
        }

        return null; // 未找到匹配的路由
      };
      const curentRoute = findParentRouteByPath(location.pathname, routes);
      console.log(curentRoute, "curentRoute");
      if (localStorage.getItem("token")) {
        if (curentRoute) {
          const authority = localStorage.getItem("authority");
          const userRole = parseInt(authority || "0");
          if (!curentRoute?.roles?.includes(userRole)) {
            history.push("/403");
          }
        } else {
          history.push("/home");
        }
      } else {
        history.push("/user/login");
      }
    },
    bgLayoutImgList: [
      {
        src: "https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr",
        left: 85,
        bottom: 100,
        height: "303px",
      },
      {
        src: "https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr",
        bottom: -68,
        right: -45,
        height: "303px",
      },
      {
        src: "https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr",
        bottom: 0,
        left: 0,
        width: "331px",
      },
    ],
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return <>{children}</>;
    },
    menu: {
      params: initialState,
      request: async (params, defaultMenuData) => {
        const filterMenuByRole: any = (menuData: any[]) => {
          const authority = localStorage.getItem("authority");
          if (!authority) return [];

          const userRole = parseInt(authority);

          return menuData
            .filter((item) => {
              // 没有设置角色的菜单默认显示
              if (!item.roles) return true;

              // 检查用户角色是否在允许的角色列表中
              return item.roles.includes(userRole);
            })
            .map((item) => {
              // 递归处理子菜单
              if (item.routes) {
                const filteredChildren = filterMenuByRole(item.routes);
                if (filteredChildren.length > 0) {
                  return {
                    ...item,
                    routes: filteredChildren,
                  };
                }
                return null;
              }
              return item;
            })
            .filter(Boolean);
        };
        // 使用角色过滤菜单
        return filterMenuByRole(defaultMenuData);
      },
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  baseURL: "http://admin.lianhongtech.com/index.php/",
  ...errorConfig,
};
